#!/usr/bin/env python
# -*- coding: utf-8 -*-

import zlib
import base64
import logging

# 获取logger
logger = logging.getLogger(__name__)

class ContentCompressor:
    """
    内容压缩和解压缩工具类
    """
    
    @staticmethod
    def compress(content: str, compression_level: int = 9) -> str:
        """
        压缩文本内容并进行Base64编码
        
        Args:
            content: 原始文本内容
            compression_level: 压缩级别 (1-9)，越高压缩率越高但速度越慢
            
        Returns:
            压缩并编码后的内容
        """
        try:
            if not content:
                return ""
            
            # 将文本转换为字节
            content_bytes = content.encode('utf-8')
            # 使用zlib进行压缩
            compressed = zlib.compress(content_bytes, level=compression_level)
            # 使用Base64编码为字符串
            encoded = base64.b64encode(compressed).decode('ascii')
            
            # 记录压缩率
            original_size = len(content_bytes)
            compressed_size = len(encoded)
            ratio = (original_size - compressed_size) / original_size * 100 if original_size > 0 else 0
            logger.debug(f"内容压缩: 原始大小={original_size}字节, 压缩后={compressed_size}字节, 压缩率={ratio:.2f}%")
            
            return encoded
        except Exception as e:
            logger.error(f"压缩内容失败: {str(e)}")
            # 如果压缩失败，返回空字符串
            return ""
    
    @staticmethod
    def decompress(encoded_content: str) -> str:
        """
        解压缩Base64编码的内容
        
        Args:
            encoded_content: 编码并压缩的内容
            
        Returns:
            原始文本内容
        """
        try:
            if not encoded_content:
                return ""
            
            # Base64解码
            compressed = base64.b64decode(encoded_content)
            # zlib解压缩
            decompressed = zlib.decompress(compressed)
            # 转换为字符串
            content = decompressed.decode('utf-8')
            
            return content
        except Exception as e:
            logger.error(f"解压内容失败: {str(e)}")
            # 如果解压失败，返回空字符串
            return "" 